package cn.trigram.example.designpattern.fsm.state;


import cn.trigram.example.designpattern.fsm.StateContext;
import cn.trigram.example.designpattern.fsm.action.Action;
import cn.trigram.example.designpattern.fsm.event.AbstractEvent;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 状态工厂，状态一般都是单例的
 */
public class FSMStateFactory {

  private static ConcurrentHashMap<String, AbstractState> stateMap = new ConcurrentHashMap<>();

  private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

  private static ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();

  private static ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();

  public static AbstractState product(String stateName, Action action) {

    try {
      writeLock.lock();
      AbstractState state = stateMap.getOrDefault(stateName, new AbstractState(stateName) {

        @Override
        public AbstractEvent handle(StateContext context) {

          return action.handle(context);
        }
      });
      stateMap.putIfAbsent(stateName, state);
      return state;
    } finally {
      writeLock.unlock();
    }
  }

}